package com.atguigu.filelock;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.Objects;

/**
 * className: FileLockDemo1
 * description:
 * date: 2023/3/10 0010-14:33
 * <p>
 * project: nio
 * package: com.atguigu.filelock
 * email: 1085844536@qq.com
 * version:
 *
 * @author WangGuojian
 */
public class FileLockDemo1 {

    public static void main(String[] args) throws IOException {
        String input = "atguigu";
        System.out.println("input:" + input);

        ByteBuffer buffer = ByteBuffer.wrap(input.getBytes());

        String filePath = Objects.requireNonNull(FileLockDemo1.class.getClassLoader().getResource("01.txt")).getPath().substring(1);
        Path path = Paths.get(filePath);

        FileChannel channel = FileChannel.open(path, StandardOpenOption.WRITE, StandardOpenOption.APPEND);
        channel.position(channel.size() - 1);

        // 加锁
        FileLock lock = channel.lock();
        System.out.println("是否共享锁：" + lock.isShared());

        channel.write(buffer);
        channel.close();

        // 读文件
        readFile(filePath);
    }

    private static void readFile(String filePath) throws IOException {
        FileReader fileReader = new FileReader(filePath);
        BufferedReader bufferedReader = new BufferedReader(fileReader);
        String str = bufferedReader.readLine();
        System.out.println("读取出内容：");
        while (str != null) {
            System.out.println(" " + str);
            str = bufferedReader.readLine();
        }
        bufferedReader.close();
        fileReader.close();
    }
}
